import { View, ScrollView, Text } from '@tarojs/components'
import { useState, useMemo, useCallback, useEffect } from 'react'
import ProductCard from './ProductCard'
import { ProductSkeleton } from '../common/Skeleton'
import EmptyState from '../common/EmptyState'

const ProductList = ({ 
  allProducts, 
  getProductsByTag, 
  productFilterTags, 
  activeFilter, 
  onFilterChange, 
  onProductClick 
}) => {
  
  if (process.env.NODE_ENV === 'development') {
    console.log('=== ProductList 组件渲染 ===')
    console.log('ProductList props:', { allProducts, activeFilter, productFilterTags })
    console.log('allProducts 类型:', typeof allProducts)
    console.log('allProducts 长度:', allProducts?.length)
    console.log('allProducts 数据:', allProducts)
  }
  
  const currentProducts = useMemo(() => {
    if (!getProductsByTag) return []
    return getProductsByTag(activeFilter)
  }, [getProductsByTag, activeFilter])
  
  if (process.env.NODE_ENV === 'development') {
    console.log(`当前标签 ${activeFilter} 的商品数量:`, currentProducts.length)
    console.log('当前标签商品数据:', currentProducts)
  }

  // 检查是否有任何数据
  const hasAnyData = allProducts && allProducts.length > 0


  if (!hasAnyData) {
    return (
      <EmptyState 
        type='products'
        actionText='刷新重试'
        onAction={() => window.location.reload()}
      />
    )
  }

  // 确保"推荐"标签在最左边
  const sortedFilterTags = useMemo(() => {
    return [...productFilterTags].sort((a, b) => {
      if (a === '推荐') return -1
      if (b === '推荐') return 1
      return 0
    })
  }, [productFilterTags])

  // 渲染商品卡片
  const renderProductCard = useCallback((product, index) => {
    return (
      <ProductCard 
        key={product.id || product._id || index} 
        product={product} 
        onClick={onProductClick}
      />
    )
  }, [onProductClick])


  return (
    <>
      {/* 筛选标签 */}
      <ScrollView 
        className='filter-tags' 
        scrollX
        showScrollbar={false}
        enhanced
      >
        {sortedFilterTags.map((tag, index) => (
          <View 
            key={index} 
            className={`filter-tag ${activeFilter === tag ? 'active' : ''}`}
            onClick={() => onFilterChange(tag)}
          >
            <Text>{tag}</Text>
          </View>
        ))}
      </ScrollView>


      {/* 商品列表 */}
      {currentProducts.length > 0 ? (
        <ScrollView 
          className='product-list' 
          scrollY
          enhanced
          showScrollbar={false}
          enableFlex
        >
          <View className='product-grid'>
            {currentProducts.map((product, index) => (
              <ProductCard 
                key={product.id || product._id || index} 
                product={product} 
                onClick={onProductClick}
              />
            ))}
          </View>
        </ScrollView>
      ) : (
        <EmptyState 
          type='products'
          title={`暂无${activeFilter}标签的商品`}
          description={`可用标签: ${productFilterTags.join(', ')}`}
        />
      )}
    </>
  )
}

export default ProductList